package cn.kicsy.www.anonymous_bbs.service;

import cn.kicsy.www.anonymous_bbs.entity.Notification;
import cn.kicsy.www.anonymous_bbs.repository.NotificationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NotificationService {
    
    @Autowired
    private NotificationRepository notificationRepository;
    
    /**
     * 创建通知
     * @param recipientIpAddress 接收通知的IP地址
     * @param type 通知类型
     * @param content 通知内容
     * @param relatedPostId 关联的帖子ID
     * @param relatedCommentId 关联的评论ID
     */
    public void createNotification(String recipientIpAddress, String type, String content, Long relatedPostId, Long relatedCommentId) {
        Notification notification = new Notification();
        notification.setRecipientIpAddress(recipientIpAddress);
        notification.setType(type);
        notification.setContent(content);
        notification.setRelatedPostId(relatedPostId);
        notification.setRelatedCommentId(relatedCommentId);
        
        notificationRepository.save(notification);
    }
    
    /**
     * 获取指定IP地址的未读通知列表
     * @param recipientIpAddress 接收通知的IP地址
     * @return 未读通知列表
     */
    public List<Notification> getUnreadNotifications(String recipientIpAddress) {
        return notificationRepository.findByRecipientIpAddressAndReadFalseOrderByCreatedAtDesc(recipientIpAddress);
    }
    
    /**
     * 获取指定IP地址的所有通知列表
     * @param recipientIpAddress 接收通知的IP地址
     * @return 所有通知列表
     */
    public List<Notification> getAllNotifications(String recipientIpAddress) {
        return notificationRepository.findByRecipientIpAddressOrderByCreatedAtDesc(recipientIpAddress);
    }
    
    /**
     * 标记单个通知为已读
     * @param notificationId 通知ID
     */
    public void markNotificationAsRead(Long notificationId) {
        notificationRepository.findById(notificationId).ifPresent(notification -> {
            notification.setRead(true);
            notificationRepository.save(notification);
        });
    }
    
    /**
     * 标记所有通知为已读
     * @param recipientIpAddress 接收通知的IP地址
     */
    public void markAllNotificationsAsRead(String recipientIpAddress) {
        List<Notification> notifications = notificationRepository.findByRecipientIpAddressAndReadFalseOrderByCreatedAtDesc(recipientIpAddress);
        for (Notification notification : notifications) {
            notification.setRead(true);
        }
        notificationRepository.saveAll(notifications);
    }
}